using System;
using System.Collections.Generic;


namespace Framework.Network
{
    public class MessagePool : Singleton<MessagePool>
    {
        private readonly Dictionary<Type, Queue<object>> m_Dictionary = new Dictionary<Type, Queue<object>>();

        public object Fetch(Type type)
        {
            Queue<object> queue;
            if (!this.m_Dictionary.TryGetValue(type, out queue))
            {
                queue = new Queue<object>();
                this.m_Dictionary.Add(type, queue);
            }
            object obj;
            if (queue.Count > 0)
            {
                obj = queue.Dequeue();
            }
            else
            {
                obj = Activator.CreateInstance(type);
            }
            return obj;
        }

        public T Fetch<T>() where T : class
        {
            T t = (T) Fetch(typeof(T));
            return t;
        }

        public void Recycle(object obj)
        {
            Type type = obj.GetType();
            Queue<object> queue;
            if (!this.m_Dictionary.TryGetValue(type, out queue))
            {
                queue = new Queue<object>();
                this.m_Dictionary.Add(type, queue);
            }
            queue.Enqueue(obj);
        }
    }
}